/**
 * @file user_socket.c
 * @author Victor Lau (1345236485@qq.com)
 * @brief 
 * @version 0.1
 * @date 2023-07-19
 * 
 * @copyright Copyright (c) 2023 Victor Lau. All rights reserved.
 * 
 */
#include "user_socket.h"
#include "include.h"
#include<netinet/in.h>
#include<arpa/inet.h>
#include "user_eth1.h"

int sockfd, connfd, len;
bool is_eth1_connect = false;
void socket_init()
{
        char *ip = NULL;
        char *get_ip = NULL;
        char connect_ip_addr[32];
        char get_ip_addr[32];
        int connectedAddrLen, ret, enable = 1;
        struct sockaddr_in server, client, connectedAddr;

        // socket create and verification
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd == -1) 
        {
                printf("socket creation failed...\n");
                exit(0);
        }

        printf("socket successfully created..\n");
        bzero(&server, sizeof(server));
        bzero(&client, sizeof(client));

        // assign IP, PORT
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = htonl(INADDR_ANY);
        server.sin_port = htons(PORT);

        setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable));

        // binding newly created socket to given IP and verification
        if ((bind(sockfd, (struct sockaddr*)&server, sizeof(server))) != 0) 
        {
                fprintf(stderr,"error in bind %s ",strerror(errno));
                printf("socket bind failed...\n");
                exit(0);
        }

        printf("socket successfully binded..\n");

        // now server is ready to listen and verification
        if ((listen(sockfd, 5)) != 0) 
        {
                printf("Listen failed...\n");
                exit(0);
        }

        printf("server listening...\n");

        len = sizeof(client);

        // accept the data packet from client and verification(blocking delay)
        connfd = accept(sockfd, (struct sockaddr*)&client, &len);
        if (connfd < 0) 
        {
                printf("server acccept failed...\n");
                exit(0);
        }
        fcntl(connfd,F_SETFL,O_NONBLOCK);                                                                                               // connection is blocked,after connection is block
        printf("server acccept the client...\n");

        connectedAddrLen = sizeof(connectedAddr);
        getsockname(connfd, (struct sockaddr *)&connectedAddr, &connectedAddrLen);      // 获取connfd表示的连接上的本地地址
        ip = inet_ntoa(connectedAddr.sin_addr);
        memcpy(connect_ip_addr, ip, 32);

        get_ip = get_eth1_static_ip();
        memcpy(get_ip_addr, get_ip + 8, strlen(get_ip) - 8 - 4);
        
        printf("get_ip = %s\n",  get_ip_addr);
        ret = strcmp(connect_ip_addr, get_ip_addr);
        printf("test ret = %d\n", ret);
        if(ret == 0)
                is_eth1_connect = true;
        else
                is_eth1_connect = false;
        
        free(get_ip);
}
